<?php
/**
 * Author: LCY<409028735@qq.com>
 * Time: 2021/11/19 14:12
 * Note:
 */
namespace app\admin\controller;
use think\captcha\Captcha;
use think\facade\Config;

class Login extends Backend
{
    /**
     * @var array
     * 不需要权限认证的控制器/方法（*表示该控制器的所有方法都不需要权限认证）
     */
    protected $noNeedAuth = ['*'];

    /**
     * @var array
     * 不需要登录就能访问
     */
    protected $noNeedLogin = ['*'];

    /**
     * 登录页
     * @return \think\response\View
     * Author: LCY<409028735@qq.com>
     * Time: 2021/11/19 22:08
     * Note:
     */
    public function index ()
    {
        //获取登录后的跳转地址
        $url = input('param.url', url('index/index'));

        if ($this->request->isPost()) {
            //验证登录
            if ($this->auth->isLogin()) {
               $this->success('已登录', $url);
            }

            //$this->checkToken();

            $username = input('post.username/s','','trim');
            $password = input('post.password/s','','trim');
            $captcha = input('post.captcha/s','','trim');
            $remember = input('post.remember/d',0,'trim');

            $data = [
                'username' => $username,
                'password' => $password,
                'captcha' => $captcha,
                'remember' => $remember,
            ];

            //验证码验证
            if (Config::get('auth.check_captcha',true) && !captcha_check($data['captcha'])) {
                $this->error('验证码有误');
            }

            //参数验证
            $this->validate($data, 'Admin.login');

            //登录账户验证
            if (!$this->auth->login($data['username'], $data['password'], $data['remember'] ? (3600 * 24 * 7) : 0 )) {
               $this->error($this->auth->getError());
            }

            $this->writeAdminLog('登录','管理员登录');
            $this->success('登录成功', $url);
        }

        //如果已经登录则不用再次登录
       if ($this->auth->isLogin() || $this->auth->autoLogin()) {
           $this->redirect($url);
       }

       $this->setSeo('用户登录');
       return $this->fetch('index');
    }


    /**
     * 自定义生成图形验证码
     * @return \think\Response
     * Author: LCY<409028735@qq.com>
     * Time: 2021/11/19 21:37
     * Note:
     */
    public function captcha()
    {
        $captcha = new Captcha(Config::get('captcha.', []));
        return $captcha->entry();
    }


    /**
     * 退出登录
     * @return \think\response\Redirect
     * Author: LCY<409028735@qq.com>
     * Time: 2021/11/19 21:39
     * Note:
     */
    public function logout()
    {
        $this->auth->logout();
        $this->redirect(url('login/index'));
    }
}